layui.use(['form'], function(){
    const $ = layui.$
        , layer = layui.layer;

    window.GetQueryString = function (name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substring(1).match(reg); //获取url中"?"符后的字符串并正则匹配
        let context = "";
        if (r != null)
            context = decodeURIComponent(r[2]);
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
    }

    let is_debug = true; // 是否开启调试模式。如开启，接口异常时会抛出异常 URL 等信息
    let response = {
        statusName: 'code', // 数据状态的字段名称
        statusCode: {
            ok: 1, // 数据状态一切正常的状态码
            redirectCode: 302,  // 重定向状态码
            tokenInvalid: 409, // token失效的状态码
        },
        msgName: 'msg', // 状态信息的字段名称
        dataName: 'data' // 数据详情的字段名称
    };
    window.setter = {
        tableName: 'jue_qi_survey', // 本地存储表名
        request: {
            tokenName: 'userToken', // 自动携带 token 的字段名。可设置 false 不携带。
            refreshTokenName: 'refresh_token', // 刷新token的字段名。
            domainName: 'https://wq.mbdede.com/addons/jueqi_survey_pro/public/index.php', // 域名
            userInfo: 'userInfo', //  保存的用户信息字段名
            cdnUrl: "cdn_url", // 远程附件前缀域名存储字段名
            activityIdArr: "activityIdArr", // 通过密码输入登录的活动ID，如果活动有设置密码，且使用密码登录成功之后会保存在此数组中
        }
    };

    let token = GetQueryString('token');
    if(token == 'undefined'){
        token = '';
    }
    if(token){
        layui.data(setter.tableName, {
            key: setter.request.tokenName
            , value: token
        });
    }else{
        token = layui.data(setter.tableName)[setter.request.tokenName];
    }

    window.axiosReq = function (options) {
        const that = this
            , success = options.success
            , error = options.error
            , request = setter.request
            , loading = options.loading
            , is_message = options.is_message
            , debug = function () {
                return is_debug ? '<br><cite>URL：</cite>' + options.url : '';
            };

        options.data = options.data || {};
        options.params = options.params || {};
        options.headers = options.headers || {};

        if (request.tokenName) {
            const sendData = typeof options.params === 'string'
                ? JSON.parse(options.params)
                : options.params;

            //自动给参数传入默认 token
            options.params[request.tokenName] = request.tokenName in sendData
                ? options.params[request.tokenName]
                : (layui.data(setter.tableName)[request.tokenName] || '');

            //自动给 Request Headers 传入 token
            options.headers[request.tokenName] = request.tokenName in options.headers
                ? options.headers[request.tokenName]
                : (layui.data(setter.tableName)[request.tokenName] || '');
        }
        options.headers["Accept"] = "application/json";
        options.headers["Content-Type"] = "application/json; charset=utf-8";
        options.headers['server'] = true;
        options.params['server'] = true;
        delete options.success;
        delete options.error;
        delete options.loading;
        if (loading){
            openLoadBox();
        }
        if(options.method === 'POST' || options.method === 'post'){
            options.data = options.params;
        }
        return axios.request($.extend({
            // 请求方式
            method: options.method,
            // 请求地址
            url: options.url,
            // URL中的查询参数
            params: options.params,
            // 响应类型
            // responseType: "JSON",
        }, options)).then(function (result) {
            if (loading) {
                closeLoadBox();
            }
            let statusCode = response.statusCode;
            let res = result.data;
            //只有 response 的 code 一切正常才执行 done
            if (parseInt(res[response.statusName]) === statusCode.ok) {
                typeof options.done === 'function' && options.done(res);
            }
            else if(parseInt(res[response.statusName]) === statusCode.redirectCode){
                let isWxMini = window.__wxjs_environment === 'miniprogram';
                if(isWxMini){
                    layer.confirm('需登录之后才可使用，是否登录？', {
                        btn: ['确定', '取消'] //按钮
                    }, function(){
                        window.location.replace(res.data.url);
                    })
                }else{
                    window.location.replace(res.data.url);
                }
            }
            else if (parseInt(res[response.statusName]) === statusCode.tokenInvalid) {
                exit();
            }
            //其它异常
            else if(is_message !== false){
                message({
                    title: res[response.msgName]
                    // , offset: "auto"
                    , icon: 2
                    , time: 1500
                });
            }
            if(parseInt(res[response.statusName]) !== statusCode.redirectCode){
                //只要 http 状态码正常、并且code不等于302，无论 response 的 code 是否正常都执行 success
                typeof success === 'function' && success(res);
            }
        })
        .catch(function (result) {
            if (loading) {
                closeLoadBox();
            }
            if(result.code !== 'ERR_NETWORK'){
                message({
                    title: '请求异常，请重试<br><cite>错误信息：</cite>' + result.message
                    // , offset: "auto"
                    , icon: 2
                    , time: 1500
                });
            }
            typeof error === 'function' && error.apply(this, arguments);
        });
    }

    //Ajax请求
    window.req = function (options) {
        const that = this
            , success = options.success
            , error = options.error
            , request = setter.request
            , loading = options.loading
            , is_message = options.is_message
            , debug = function () {
                return is_debug
                    ? '<br><cite>URL：</cite>' + options.url
                    : '';
            };
        options.data = options.data || {};
        options.headers = options.headers || {};

        if (request.tokenName) {
            const sendData = typeof options.data === 'string'
                ? JSON.parse(options.data)
                : options.data;

            //自动给参数传入默认 token
            options.data[request.tokenName] = request.tokenName in sendData
                ? options.data[request.tokenName]
                : (layui.data(setter.tableName)[request.tokenName] || '');

            //自动给 Request Headers 传入 token
            options.headers[request.tokenName] = request.tokenName in options.headers
                ? options.headers[request.tokenName]
                : (layui.data(setter.tableName)[request.tokenName] || '');
        }

        options.headers['server'] = true;

        delete options.success;
        delete options.error;
        delete options.loading;

        if (loading){
            openLoadBox();
        }
        return $.ajax($.extend({
            type: 'get'
            , dataType: 'json'
            , success: function (res) {
                let statusCode = response.statusCode;

                //只有 response 的 code 一切正常才执行 done
                if (parseInt(res[response.statusName]) === statusCode.ok) {
                    typeof options.done === 'function' && options.done(res);
                }
                else if(parseInt(res[response.statusName]) === statusCode.redirectCode){
                    let isWxMini = window.__wxjs_environment === 'miniprogram';
                    if(isWxMini){
                        layer.confirm('需登录之后才可使用，是否登录？', {
                            btn: ['确定', '取消'] //按钮
                        }, function(){
                            window.location.replace(res.data.url);
                        })
                    }else{
                        window.location.replace(res.data.url);
                    }
                }
                else if (parseInt(res[response.statusName]) === statusCode.tokenInvalid) {
                    exit();
                }
                //其它异常
                else if(is_message !== false){
                    message({
                        title: res[response.msgName]
                        // , offset: "auto"
                        , icon: 2
                        , time: 1500
                    });
                }
                if(parseInt(res[response.statusName]) !== statusCode.redirectCode){
                    //只要 http 状态码正常、并且code不等于302，无论 response 的 code 是否正常都执行 success
                    typeof success === 'function' && success(res);
                }
            }
            , error: function (e, code) {
                message({
                    title: '请求异常，请重试<br><cite>错误信息：</cite>' + code
                    // , offset: "auto"
                    , icon: 2
                    , time: 1500
                });
                typeof error === 'function' && error.apply(this, arguments);
            },
            complete: function(res){
                if (loading) {
                    closeLoadBox();
                }
            }
        }, options));
    };
    // 打开加载层
    window.openLoadBox = function (styleType = '') {
        if(styleType === ''){
            layer.load();
        }else{
            layer.load(styleType);
        }
    }
    // 关闭加载层
    window.closeLoadBox = function () {
        layer.closeAll('loading');
    }
    // 消息提示
    window.message = function (options) {
        const title = options.title;
        delete options.title;
        if(typeof options.callback === 'function'){
            return layer.msg(title, $.extend({
                icon: 1
                ,time: 1500
                ,offset: "auto"
            }, options), options.callback)
        }else{
            return layer.msg(title, $.extend({
                icon: 1
                ,time: 1500
                ,offset: "auto"
            }, options))
        }
    };
    //弹窗
    window.popup = function (options) {
        const success = options.success
            , skin = options.skin;

        delete options.success;
        delete options.skin;

        return layer.open($.extend({
            type: 1
            , title: '提示'
            , area: ['500px', '750px']
            , content: ''
            , id: 'LAY-system-view-popup'
            , skin: 'layui-layer-admin' + (skin ? ' ' + skin : '')
            , shadeClose: true
            , closeBtn: false
            , success: function (layero, index) {
                let elemClose = $('<i class="layui-icon" close>&#x1006;</i>');
                layero.append(elemClose);
                elemClose.on('click', function () {
                    layer.close(index);
                });
                typeof success === 'function' && success.apply(this, arguments);
            }
        }, options))
    };
    //异常提示
    window.error = function (content, options) {
        return popup($.extend({
            content: content
            , maxWidth: 300
            //,shade: 0.01
            , offset: 't'
            , anim: 6
            , id: 'LAY_adminError'
        }, options))
    };

    /**
     * 远程附件文件转换
     * @param file
     * @param domain // 是否携带域名
     * @returns {string}
     */
    window.cdnUrlFilter = function (file = '', domain = false){
        if(!file){
            return file;
        }
        let cdnUrl = layui.data(setter.tableName)[setter.cdnUrl];
        if (!cdnUrl){
            cdnUrl = '';
        }
        let fileUrl = file;
        if(file.indexOf("http:") > -1 || file.indexOf("https:") > -1) {
            cdnUrl = '';
        }else if(file.indexOf("../static/") > -1 || file.indexOf("../storage/") > -1){

        }else if(file.indexOf("/static/") > -1 || file.indexOf("/storage/") > -1){
            fileUrl = '../../..' + file;
        }else{
            fileUrl = cdnUrl + fileUrl;
        }
        if(domain === true){
            return cdnUrl + file;
        }else{
            return fileUrl;
        }
    }

    /**
     * 清除 token
     */
    window.exit = function () {
        // 清空本地记录的 token
        layui.data(setter.tableName, {
            key: setter.request.tokenName
            , remove: true
        });

        // 清空本地记录的刷新 token
        layui.data(setter.tableName, {
            key: setter.request.refreshTokenName
            , remove: true
        });

        // 清空本地记录的用户消息
        layui.data(setter.tableName, {
            key: setter.request.userInfo
            , remove: true
        });

        // 刷新当前页面
        let url = window.location.href;
        if(token && url.indexOf(token)){
            url = url.replace(token, '');
        }else if(url.indexOf("token=") > -1){
            url = url.replace("token=", 't=');
        }else if(url.indexOf("/program/view/") > -1){
            url = "../program/index.html";
        }else if(url.indexOf("/frontend/view/") > -1){
            let activity_id = GetQueryString('activity_id');
            let flag = GetQueryString('flag');
            url = "../activity/login_web.html?activity_id=" + activity_id + '&flag=' + flag;
        }
        window.location.replace(url);
    };

})